import os
import pwd

#: Skywalker Logger Level (info, debug, warn, error)
SW_LOGLEVEL = str(os.environ.get("SW_LOGLEVEL", "info")).lower()
SLURM_CACHE_KEY = "SLURM_SCRATCH"

# We first check if we are using SLURM.
if SLURM_CACHE_KEY in os.environ:
    DEFAULT_CACHE_DIR = os.environ[SLURM_CACHE_KEY]

# If not using slurm, we go to /media/workspace
else:
    _current_user_name = pwd.getpwuid(os.getuid())[0]
    try:
        # NOTE to DU Chen, PENG Bo and Larry
        # by default `/media/workspace/{_current_user_name}/.skywalker/cache` is used as the cache
        # the directory should be cleaned up periodoically, maybe with a crontab
        # in the future we probably could have more solid mechanism to manage the cache
        DEFAULT_CACHE_DIR = "~/workspace/{}/.skywalker/cache".format(
            _current_user_name
        )
        if not os.path.exists(DEFAULT_CACHE_DIR):
            os.makedirs(DEFAULT_CACHE_DIR, exist_ok=True)
    except PermissionError:
        # or `$HOME/.skywalker/cache` if in a remote setting, for example GitHub Action runner container
        DEFAULT_CACHE_DIR = "~/.skywalker/cache"
        if not os.path.exists(DEFAULT_CACHE_DIR):
            os.makedirs(DEFAULT_CACHE_DIR, exist_ok=True)

# Matplotlib cannot find home dir for user in SLURM, we assign a new cache
# folder for it
os.environ["MPLCONFIGDIR"] = os.path.join(DEFAULT_CACHE_DIR, "matplotlib_cache")
